package com.health.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.health.dao.CheckGroupMapper;
import com.health.pojo.CheckGroup;
import com.health.vo.PageResult;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService{
    @Resource
    private CheckGroupMapper checkGroupMapper;

    @Override
    public PageResult<CheckGroup> findPage(Integer pageNow, Integer pageSize, String query) {
        //分页插件
        PageHelper.startPage(pageNow, pageSize);
        //执行查询，Page中包含了查询到的总数，以及分页后的列表
        Page<CheckGroup> page = checkGroupMapper.findByQuery(query);

        //封装查询到的总数与列表
        return new PageResult<>(page.getTotal(), page.getResult());    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Integer id) {

        //到关联表中查询该检查组是否有被某个套餐使用
        int count = checkGroupMapper.findCountByCheckGroupId(id);
        if (count > 0) {
            //已被使用，抛出异常，取消删除操作
            throw new RuntimeException("有套餐正在使用该检查组，无法删除！");
        }

        //未被使用则先删除检查组与检查项的关联
        checkGroupMapper.deleteCheckGroupCheckItem(id);

        //再删除检查组
        return checkGroupMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(CheckGroup checkGroup, Integer[] checkItemIds) {
        //新增检查组
        int count = checkGroupMapper.add(checkGroup);

        //新增检查组与检查项的关联关系
        if (checkItemIds != null && checkItemIds.length > 0) {
            //获取新增的检查组id
            Integer checkGroupId = checkGroup.getId();
            //添加关联关系
            checkGroupMapper.addCheckGroupCheckItem(checkGroupId, checkItemIds);
        }

        return count;
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupMapper.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIds(Integer id) {
        return checkGroupMapper.findCheckItemIds(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(CheckGroup checkGroup, Integer[] checkItemIds) {
        //更新检查组信息
        int count = checkGroupMapper.update(checkGroup);

        //删除检查组与检查项的关联信息
        Integer checkGroupId = checkGroup.getId();
        checkGroupMapper.deleteCheckGroupCheckItem(checkGroupId);
        //添加新关系
        if (checkItemIds != null && checkItemIds.length > 0) {
            checkGroupMapper.addCheckGroupCheckItem(checkGroupId, checkItemIds);
        }

        return count;
    }
}
